<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script lang="ts" setup>
import { ref, computed, unref, inject } from 'vue'
import { BasicModal, useModalInner } from '@/components/Modal'
import { BasicForm, useForm } from '@/components/Form'
import { formSchema } from './org.data'
import { getOrgTree, addorUpdateOrg } from '@/api/sys/org'

defineOptions({ name: 'OrgModal' })

const emit = defineEmits(['success', 'register'])

// 父子组件通过porject inject相互通信
const callMethodInTree = inject('callMethodInTree') as Function;

const isUpdate = ref(true)
const orgId = ref('')
const orgCode = ref()

const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
  labelWidth: 100,
  baseColProps: { span: 24 },
  schemas: formSchema,
  showActionButtonGroup: false,
})

const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  resetFields()
  setModalProps({ confirmLoading: false })
  isUpdate.value = !!data?.isUpdate
  orgCode.value = data?.orgCode
  if (unref(isUpdate)) {
    // console.log(data.record);

    orgId.value = data.record.orgId
    setFieldsValue({
      ...data.record,
    })
  }
  const treeData = await getOrgTree()
  updateSchema({
    field: 'parentOrgId',
    componentProps: { treeData },
  })
})

const getTitle = computed(() => (!unref(isUpdate) ? '新增组织' : '编辑组织'))

async function handleSubmit() {
  try {
    const values = await validate()
    setModalProps({ confirmLoading: true })
    let params: any = { ...values }
    if (unref(isUpdate)) {
      params = { ...params, orgId: orgId.value }
    }
    const res = await addorUpdateOrg(params)
    !res && closeModal()
    callMethodInTree && callMethodInTree();
    emit('success', { isUpdate: unref(isUpdate), values: { ...values } })
  } finally {
    setModalProps({ confirmLoading: false })
  }
}

</script>
